'use strict';

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const glob = require('glob');
const path = require('path');
const { camelCase } = require('lodash');
const debug = require('debug')('koa-mvc');

const app = new Koa();
app.use(bodyParser());

const router = new Router();
app.router = router;
app.appPath = process.cwd();
app.controller = {};

const getControllers = () => {
  return new Promise((resolve, reject) => {
    glob('./app/controllers/*.js', app.appPath, (err, files) => {
      if (err) {
        return reject(err);
      }
      files.map((file) => {
        const ctrlName = camelCase(path.parse(file).name);
        const ctrl = require(file);
        if (typeof ctrl == 'object') {
          app.controller[ctrlName] = ctrl;
        } else if (typeof ctrl == 'function') {
          app.controller[ctrlName] = new ctrl();
        }
      });
      resolve();
    });
  });
};

app.use(async (ctx, next) => {
  await getControllers();
  require('./app/configs/routes')(app);
  await next();
});
app.use(app.router.routes());
app.use(app.router.allowedMethods());
app.listen(3000);
